package org.fly.api.demo.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.captcha.AbstractCaptcha;
import cn.hutool.captcha.generator.CodeGenerator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.RequiredArgsConstructor;

import org.apache.commons.lang3.StringUtils;
import org.fly.api.common.core.R;
import org.fly.api.common.core.constant.Constants;
import org.fly.api.common.core.constant.GlobalConstants;
import org.fly.api.common.core.exception.user.CaptchaException;
import org.fly.api.common.core.exception.user.CaptchaExpireException;
import org.fly.api.common.redis.utils.RedissonUtil;
import org.fly.api.common.web.enums.CaptchaType;
import org.fly.api.common.web.properties.CaptchaProperties;
import org.fly.api.common.core.domain.vo.CaptchaVo;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Duration;

/**
 * 验证码操作处理
 *
 * @author Blue
 * @date 2023/12/12
 */
@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/captcha")
public class CaptchaController {

    private final CaptchaProperties captchaProperties;


    /**
     * 生成验证码
     *
     * @return {@link R}<{@link CaptchaVo}>
     */
    @GetMapping("/captchaImage")
    public R<CaptchaVo> getCode() {
        CaptchaVo captchaVo = new CaptchaVo();
        boolean captchaEnabled = captchaProperties.getEnable();
        if (!captchaEnabled) {
            captchaVo.setCaptchaEnabled(false);
            return R.ok(captchaVo);
        }
        // 保存验证码信息
        String uuid = IdUtil.simpleUUID();
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + uuid;
        // 生成验证码
        CaptchaType captchaType = captchaProperties.getType();
        boolean isMath = CaptchaType.MATH == captchaType;
        Integer length = isMath ? captchaProperties.getNumberLength() : captchaProperties.getCharLength();
        CodeGenerator codeGenerator = ReflectUtil.newInstance(captchaType.getClazz(), length);
        AbstractCaptcha captcha = SpringUtil.getBean(captchaProperties.getCategory().getClazz());
        captcha.setGenerator(codeGenerator);
        captcha.createCode();
        String code = captcha.getCode();
        if (isMath) {
            ExpressionParser parser = new SpelExpressionParser();
            Expression exp = parser.parseExpression(StringUtils.remove(code, "="));
            code = exp.getValue(String.class);
        }
        RedissonUtil.setCacheObject(verifyKey, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        captchaVo.setUuid(uuid);
        captchaVo.setImg(captcha.getImageBase64());
        return R.ok(captchaVo);
    }

    /**
     * @param code 验证码
     * @param uuid 唯一标识
     * @return {@link R}<{@link String}>
     */
    @GetMapping("/validateCaptcha")
    public R<String> validateCaptcha(String code, String uuid){
        String verifyKey = GlobalConstants.CAPTCHA_CODE_KEY + StringUtils.defaultString(uuid, "");
        String captcha = RedissonUtil.getCacheObject(verifyKey);
        RedissonUtil.deleteObject(verifyKey);
        if (captcha == null) {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException();
        }
        return R.ok("OK");
    }

}
